

import React, { useState, useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import styles from './styles.module.css';

interface FoodData {
  name: string;
  image: string;
  caloriesPer100g: number;
  proteinPer100g: number;
  carbPer100g: number;
  fatPer100g: number;
}

interface NutritionData {
  totalCalories: number;
  totalProtein: number;
  totalCarb: number;
  totalFat: number;
}

const CalculationResultPage: React.FC = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [foodData, setFoodData] = useState<FoodData | null>(null);
  const [nutritionData, setNutritionData] = useState<NutritionData>({
    totalCalories: 0,
    totalProtein: 0,
    totalCarb: 0,
    totalFat: 0
  });
  const [portionValue, setPortionValue] = useState<number>(200);
  const [portionUnit, setPortionUnit] = useState<string>('g');
  const [isAddingToRecord, setIsAddingToRecord] = useState<boolean>(false);

  // 模拟食物数据库
  const foodDatabase: Record<string, FoodData> = {
    "food1": {
      name: "鸡胸肉沙拉",
      image: "https://s.coze.cn/image/C3k89Fe9CbI/",
      caloriesPer100g: 225,
      proteinPer100g: 17.5,
      carbPer100g: 14,
      fatPer100g: 6
    },
    "food2": {
      name: "燕麦粥",
      image: "https://s.coze.cn/image/u2zgy803XXw/",
      caloriesPer100g: 213,
      proteinPer100g: 7,
      carbPer100g: 40,
      fatPer100g: 2.5
    },
    "food3": {
      name: "苹果",
      image: "https://s.coze.cn/image/vbiL7ylDDHE/",
      caloriesPer100g: 52,
      proteinPer100g: 0.3,
      carbPer100g: 14,
      fatPer100g: 0.2
    }
  };

  // 设置页面标题
  useEffect(() => {
    const originalTitle = document.title;
    document.title = '食算 - 计算结果';
    return () => { document.title = originalTitle; };
  }, []);

  // 加载食物数据
  useEffect(() => {
    const foodId = searchParams.get('foodId') || 'food1';
    const portionValueParam = parseFloat(searchParams.get('portionValue') || '200');
    const portionUnitParam = searchParams.get('portionUnit') || 'g';

    setPortionValue(portionValueParam);
    setPortionUnit(portionUnitParam);

    const food = foodDatabase[foodId] || foodDatabase['food1'];
    setFoodData(food);

    // 计算营养成分
    let multiplier = portionValueParam / 100;
    if (portionUnitParam !== 'g') {
      multiplier = portionValueParam;
    }

    const totalCalories = Math.round(food.caloriesPer100g * multiplier);
    const totalProtein = Math.round(food.proteinPer100g * multiplier * 10) / 10;
    const totalCarb = Math.round(food.carbPer100g * multiplier * 10) / 10;
    const totalFat = Math.round(food.fatPer100g * multiplier * 10) / 10;

    setNutritionData({
      totalCalories,
      totalProtein,
      totalCarb,
      totalFat
    });
  }, [searchParams]);

  // ESC键关闭弹窗
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        navigate(-1);
      } else if (e.key === 'Enter' && !isAddingToRecord) {
        handleConfirmAdd();
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    return () => {
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [navigate, isAddingToRecord]);

  const handleCloseModal = () => {
    navigate(-1);
  };

  const handleCancel = () => {
    navigate(-1);
  };

  const handleConfirmAdd = () => {
    if (isAddingToRecord) return;

    setIsAddingToRecord(true);
    const foodId = searchParams.get('foodId') || 'food1';

    // 模拟添加到记录的操作
    console.log('添加食物到记录:', { 
      foodId, 
      portionValue, 
      portionUnit 
    });

    // 延迟跳转到首页
    setTimeout(() => {
      navigate('/home');
    }, 1000);
  };

  const handleBackdropClick = (e: React.MouseEvent<HTMLDivElement>) => {
    if (e.target === e.currentTarget) {
      navigate(-1);
    }
  };

  if (!foodData) {
    return (
      <div className={styles.pageWrapper}>
        <div className="fixed inset-0 modal-backdrop flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl shadow-modal w-full max-w-md p-6">
            <div className="text-center">
              <i className="fas fa-spinner fa-spin text-2xl text-primary mb-4"></i>
              <p className="text-text-secondary">加载中...</p>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className={styles.pageWrapper}>
      {/* 模态弹窗背景遮罩 */}
      <div 
        className={`fixed inset-0 ${styles.modalBackdrop} flex items-center justify-center z-50 p-4`}
        onClick={handleBackdropClick}
      >
        {/* 模态弹窗内容 */}
        <div className={`bg-white rounded-2xl shadow-modal w-full max-w-md ${styles.modalEnter}`}>
          {/* 弹窗头部 */}
          <div className="flex items-center justify-between p-6 border-b border-border-light">
            <h2 className="text-xl font-bold text-text-primary flex items-center">
              <i className="fas fa-calculator text-primary mr-3"></i>
              计算结果
            </h2>
            <button 
              onClick={handleCloseModal}
              className="text-text-secondary hover:text-text-primary transition-colors p-1"
            >
              <i className="fas fa-times text-lg"></i>
            </button>
          </div>
          
          {/* 弹窗内容区 */}
          <div className="p-6">
            {/* 食物信息 */}
            <div className="flex items-center space-x-4 mb-6">
              <img 
                src={foodData.image}
                alt={foodData.name}
                className="w-16 h-16 rounded-xl object-cover"
                data-category="食物"
              />
              <div>
                <h3 className="text-lg font-semibold text-text-primary">{foodData.name}</h3>
                <p className="text-sm text-text-secondary">份量：{portionValue}{portionUnit}</p>
              </div>
            </div>
            
            {/* 卡路里总量 */}
            <div className="bg-primary bg-opacity-5 rounded-xl p-4 mb-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-text-secondary text-sm">总卡路里</p>
                  <p className="text-3xl font-bold text-primary">{nutritionData.totalCalories} kcal</p>
                </div>
                <div className="w-12 h-12 bg-primary bg-opacity-10 rounded-lg flex items-center justify-center">
                  <i className="fas fa-fire text-primary text-xl"></i>
                </div>
              </div>
            </div>
            
            {/* 营养成分 */}
            <div className="space-y-3 mb-6">
              <h4 className="font-semibold text-text-primary mb-3">营养成分</h4>
              
              {/* 蛋白质 */}
              <div className={`${styles.nutritionItem} flex items-center justify-between p-3 rounded-lg`}>
                <div className="flex items-center space-x-3">
                  <div className="w-8 h-8 bg-secondary bg-opacity-10 rounded-lg flex items-center justify-center">
                    <i className="fas fa-drumstick-bite text-secondary text-sm"></i>
                  </div>
                  <span className="text-text-primary">蛋白质</span>
                </div>
                <span className="font-semibold text-text-primary">{nutritionData.totalProtein}g</span>
              </div>
              
              {/* 碳水化合物 */}
              <div className={`${styles.nutritionItem} flex items-center justify-between p-3 rounded-lg`}>
                <div className="flex items-center space-x-3">
                  <div className="w-8 h-8 bg-tertiary bg-opacity-10 rounded-lg flex items-center justify-center">
                    <i className="fas fa-bread-slice text-tertiary text-sm"></i>
                  </div>
                  <span className="text-text-primary">碳水化合物</span>
                </div>
                <span className="font-semibold text-text-primary">{nutritionData.totalCarb}g</span>
              </div>
              
              {/* 脂肪 */}
              <div className={`${styles.nutritionItem} flex items-center justify-between p-3 rounded-lg`}>
                <div className="flex items-center space-x-3">
                  <div className="w-8 h-8 bg-info bg-opacity-10 rounded-lg flex items-center justify-center">
                    <i className="fas fa-oil-can text-info text-sm"></i>
                  </div>
                  <span className="text-text-primary">脂肪</span>
                </div>
                <span className="font-semibold text-text-primary">{nutritionData.totalFat}g</span>
              </div>
            </div>
          </div>
          
          {/* 弹窗底部操作按钮 */}
          <div className="flex items-center justify-end space-x-3 p-6 border-t border-border-light bg-gray-50 rounded-b-2xl">
            <button 
              onClick={handleCancel}
              className="px-6 py-2 border border-border-light text-text-secondary rounded-lg hover:bg-white transition-colors"
            >
              取消
            </button>
            <button 
              onClick={handleConfirmAdd}
              disabled={isAddingToRecord}
              className={`px-6 py-2 rounded-lg transition-colors flex items-center space-x-2 ${
                isAddingToRecord 
                  ? 'bg-secondary text-white' 
                  : 'bg-primary text-white hover:bg-indigo-600'
              }`}
            >
              <i className={`fas ${isAddingToRecord ? 'fa-check' : 'fa-plus'}`}></i>
              <span>{isAddingToRecord ? '添加成功' : '添加到记录'}</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default CalculationResultPage;

